<?php

namespace App\Services;

use App\Models\Product;
use App\Models\HotSearch;
use App\Models\SearchHistory;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

class SearchService
{
    /**
     * MySQL 全文搜索
     */
    public function search(string $keyword, array $filters = []): LengthAwarePaginator
    {
        $query = Product::query()
            ->with(['images', 'categories'])
            ->where('is_active', true);

        // 全文搜索
        if (!empty($keyword)) {
            $query->whereRaw("MATCH(name, description, sku) AGAINST(? IN BOOLEAN MODE)", [$keyword])
                ->orderByRaw("
                    CASE 
                        WHEN name LIKE ? THEN 1
                        WHEN sku LIKE ? THEN 2
                        ELSE 3
                    END
                ", ["%{$keyword}%", "%{$keyword}%"]);
        }

        // 分类筛选
        if (!empty($filters['category_id'])) {
            $query->whereHas('categories', function ($q) use ($filters) {
                $q->where('categories.id', $filters['category_id']);
            });
        }

        // 价格区间
        if (!empty($filters['min_price'])) {
            $query->where('price', '>=', $filters['min_price']);
        }
        if (!empty($filters['max_price'])) {
            $query->where('price', '<=', $filters['max_price']);
        }

        // 排序
        if (!empty($filters['sort'])) {
            switch ($filters['sort']) {
                case 'price_asc':
                    $query->orderBy('price', 'asc');
                    break;
                case 'price_desc':
                    $query->orderBy('price', 'desc');
                    break;
                case 'newest':
                    $query->orderBy('created_at', 'desc');
                    break;
            }
        }

        return $query->paginate(20);
    }

    /**
     * 搜索建议（基于产品名称）
     */
    public function suggestions(string $keyword, int $limit = 5): Collection
    {
        return Product::where('is_active', true)
            ->where('name', 'like', "%{$keyword}%")
            ->select('id', 'name', 'slug')
            ->limit($limit)
            ->get();
    }

    /**
     * 记录搜索历史
     */
    public function recordSearchHistory(string $keyword, int $resultCount, ?int $userId = null, ?string $sessionId = null): void
    {
        SearchHistory::create([
            'user_id' => $userId,
            'session_id' => $sessionId,
            'keyword' => $keyword,
            'result_count' => $resultCount,
        ]);

        // 更新热门搜索
        $hotSearch = HotSearch::where('keyword', $keyword)->first();
        
        if ($hotSearch) {
            $hotSearch->incrementSearchCount();
        } else {
            HotSearch::create([
                'keyword' => $keyword,
                'search_count' => 1,
                'last_searched_at' => now(),
            ]);
        }
    }

    /**
     * 获取搜索历史
     */
    public function getSearchHistory(?int $userId = null, ?string $sessionId = null, int $limit = 10): Collection
    {
        $query = SearchHistory::query();

        if ($userId) {
            $query->where('user_id', $userId);
        } elseif ($sessionId) {
            $query->where('session_id', $sessionId);
        }

        return $query->latest()
            ->limit($limit)
            ->get();
    }

    /**
     * 删除搜索历史
     */
    public function deleteSearchHistory(int $id, ?int $userId = null, ?string $sessionId = null): bool
    {
        $query = SearchHistory::where('id', $id);

        if ($userId) {
            $query->where('user_id', $userId);
        } elseif ($sessionId) {
            $query->where('session_id', $sessionId);
        }

        return $query->delete() > 0;
    }

    /**
     * 清空搜索历史
     */
    public function clearSearchHistory(?int $userId = null, ?string $sessionId = null): void
    {
        $query = SearchHistory::query();

        if ($userId) {
            $query->where('user_id', $userId);
        } elseif ($sessionId) {
            $query->where('session_id', $sessionId);
        }

        $query->delete();
    }

    /**
     * 获取热门搜索
     */
    public function getHotSearches(int $limit = 10): Collection
    {
        return HotSearch::orderBy('search_count', 'desc')
            ->orderBy('last_searched_at', 'desc')
            ->limit($limit)
            ->get();
    }
}

